import logging

from flask import Blueprint

siteMessage_bp = Blueprint('site_message', __name__)
from Test import db

from flask import Flask, request, jsonify, abort, g
from utils.tokenUtil import *
import datetime
from siteMessage.StatusEnum import StatusEnum


class SiteMessageInfo(db.Model):
    __tablename__ = 'site_message_info'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    user_id = db.Column(db.Integer, nullable=True)
    title = db.Column(db.Text, nullable=True, comment='信息标题')
    content_detail = db.Column(db.Text, nullable=True, comment='消息详情')
    create_time = db.Column(db.DateTime, default=datetime.datetime.utcnow, comment='创建时间')
    read_status = db.Column(db.String(255), nullable=True, comment='是否已读状态')
    importance_level = db.Column(db.String(255), nullable=True, comment='重要程度')
    message_type = db.Column(db.String(255), nullable=True, comment='消息类型')
    information_summary = db.Column(db.Text, nullable=True, comment='信息摘要')


def to_dict_value(self):
    return {
        'id': self.id,
        'title': self.title,
        'content_detail': self.content_detail,
        'create_time': self.create_time,
        'read_status': self.read_status,
        'importance_level': self.importance_level,
        'message_type': self.message_type,
        'user_name': self.user_name,
        'information_summary': self.information_summary
    }


##根据用户名称获取用户消息接口
@siteMessage_bp.route('/get-messages', methods=['GET'])
@token_required
def get_messages_list():
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)

        read_status = request.args.get('read_status', '')
        importance_level = request.args.get('importance_level', '')
        message_type = request.args.get('message_type', '')

        query = SiteMessageInfo.query.filter_by(user_id=g.user_id)
        if read_status:
            query = query.filter(SiteMessageInfo.read_status == read_status)
        if importance_level:
            query = query.filter(SiteMessageInfo.importance_level == importance_level)
        if message_type:
            query = query.filter(SiteMessageInfo.message_type == message_type)

        query = query.order_by(SiteMessageInfo.create_time.desc())
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        data = [to_dict_value(msg) for msg in pagination.items]

        return jsonify({
            'data': {
                'data': data,
                'total': pagination.total,
                'pages': pagination.pages,
                'current_page': pagination.page,
                'per_page': pagination.per_page,
            },
            'message': 'get user message success',
            'status': 200
        })
    except Exception as e:
        logging.error('获取用户消息失败，失败原因：%s', str(e))
        return jsonify({
            'data': [],
            'message': 'exception',
            'status': 500
        })


## 根据消息id获取用户信息接口，调用该接口时，将该信息已读状态设置为已读
@siteMessage_bp.route('/message-detail', methods=['POST'])
@token_required
def get_message_content():
    try:
        request_data = request.json
        message_id = request_data.get('message_id')

        message = SiteMessageInfo.query.filter_by(user_id=g.user_id).filter_by(id=message_id).first()
        if message is None:
            return jsonify({
                'data': {},
                'message': 'data not exist',
                'status': 500
            })

        ##更改消息是否已读状态为已读
        message.read_status = StatusEnum.READ.value
        db.session.add(message)
        data = {
            "id": message.id,
            "title": message.title,
            "content_detail": message.content_detail,
            "create_time": message.create_time,
            "read_status": message.read_status,
            "importance_level": message.importance_level,
            "message_type": message.message_type,
            'user_name': message.user_name,
            'information_summary': message.information_summary
        }

        return jsonify({
            'data': data,
            'message': 'success',
            'status': 200
        })
    except Exception as e:
        logging.error('获取用户消息失败,错误原因为：%s', str(e))
        return jsonify({
            'data': [],
            'message': 'exception',
            'status': 500
        })


##根据用户名称、统计重要程度为重要的 未读消息条数
@siteMessage_bp.route('/get_important_num', methods=['POST'])
@token_required
def get_important_message_num():
    try:
        request_data = request.json
        importance_level = request_data.get('importance_level', StatusEnum.IMPORTANCE.value)

        query = SiteMessageInfo.query.filter_by(user_id=g.user_id)
        query = query.filter(SiteMessageInfo.read_status == StatusEnum.UNREAD.value)
        if importance_level:
            query = query.filter(SiteMessageInfo.importance_level == importance_level)
        num = str(query.count())

        return jsonify({
            'data': num,
            'message': 'success',
            'status': 200
        })
    except Exception as e:
        logging.error('获取用户重要信息条数失败，失败原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })



##批量修改已读状态接口
@siteMessage_bp.route('/change_status_by_ids', methods=['POST'])
@token_required
def change_status_by_ids():
    try:
        request_data = request.json
        ids = request_data.get('ids',[])

        if len(ids) != 0:
            query = SiteMessageInfo.query.filter_by(user_id=g.user_id)
            query.filter(SiteMessageInfo.id.in_(ids)).update(
            {'read_status': StatusEnum.READ.value},
            synchronize_session=False
            )
            db.session.commit()

            return jsonify({
            'data': '',
            'message': 'success',
            'status': 200
            })
        else:
            return jsonify({
            'data': '',
            'message': 'ids must not be empty',
            'status': 500
            })
    except Exception as e:
        logging.error('批量修改信息已读状态失败，失败原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })


@siteMessage_bp.route('/all_message_read', methods=['GET'])
@token_required
def all_message_read():
    try:
        messages = SiteMessageInfo.query.filter_by(user_id=g.user_id).all()
        if len(messages) != 0:
            for message in messages:
                message.read_status = StatusEnum.READ.value
            db.session.commit()

        return jsonify({
            'data': '',
            'message': 'success',
            'status': 200
            })

    except Exception as e:
        logging.error('批量修改信息已读状态失败，失败原因为：%s', str(e))
        return jsonify({
            'data': '',
            'message': 'exception',
            'status': 500
        })

